package com.stu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.common.R;
import com.stu.pojo.Account;
import com.stu.pojo.AccountFlow;
import com.stu.pojo.Channel;
import com.stu.pojo.User;
import com.stu.service.IAccountService;
import com.stu.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-12-20
 */
@RestController
@Slf4j
@RequestMapping("/account")
public class AccountController {
    @Autowired
    IAccountService accountService;

    //获取所有的账户名
    @GetMapping
    public R getAllAccountName(){
        List<Account> list = accountService.list();
        List<String> nameList = list.stream().map(Account::getName).collect(Collectors.toList());
        return R.success(nameList);
    }


    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        Page<Account> userPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Account> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Account::getName,name);
        qw.orderByDesc(Account::getUpdateTime);
        qw.orderByAsc(Account::getName);
        accountService.page(userPage,qw);
        return R.success(userPage);
    }

    @PostMapping
    public R save(@RequestBody Account account){
        account.setStatus(1);
        // 空值赋0
        if(Objects.isNull(account.getCount())){
            account.setCount(new BigDecimal(0));
        }
        accountService.save(account);
        return R.success("新增成功");
    }

    //退款
    @Transactional
    @PostMapping("/zhichuMoney")
    public R zhichuMoney(@RequestBody Map<String,String> map){
        log.info("map:{}",map);
        R r = accountService.zhichuMoney(map);
        return r;
    }


    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        Account account = accountService.getById(id);
        if (account != null){
            return R.success(account);
        }
        return R.error("没有查询到对应账户信息");
    }

    @PutMapping
    public R update(@RequestBody Account account){

        boolean flag = accountService.updateById(account);
        return flag ? R.success("修改成功"):R.error("修改失败");
    }

    //缴费操作
    @PostMapping("/pay")
    public R pay(@RequestBody AccountFlow accountFlow){
        boolean flag = accountService.pay(accountFlow);
        return flag ? R.success("操作成功"):R.error("操作失败");
    }
}

